
#include "mainwindow.h"
#include "adapter/articleupdater.h"
#include "qtimer.h"
#include "ui_mainwindow.h"
#include "utils/qpixmapmeger.h"

#include <QClipboard>
#include <QMenu>
#include <QMessageBox>
#include <httpclient.h>
#include <keypresseater.h>
#include <mouseeater.h>
#include <moveeater.h>

#include <adapter/article.h>
#include <adapter/articlemanager.h>


MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
  , ui(new Ui::MainWindow)
  , isFirst(true)
{
    ui->setupUi(this);

    // setWindowFlags(Qt::FramelessWindowHint);

    // new MoveEater(ui->header, this);
    // new MoveEater(ui->body, this);

//    Response resp = HttpClient::instance().get(article_backend + "/api/article/list");
//    QVariantList list = resp.toList();
//    for (auto var : list) {
//        auto map = var.toMap();

//        struct Article article = Article::fromVariantMap(map);

//        QListWidgetItem *item = new QListWidgetItem(article.title);
//        item->setData(990, article.article_id);
//        ui->article_list->addItem(item);
//    }


    ui->splitter_1->setSizes(QList<int>() << 300 << 800);
    ui->splitter_2->setSizes(QList<int>() << 1000 << 200);

    // 创建 ArticleManager
    manager = new ArticleManager(this);
    manager->setSyncMode(true);

    connect(manager, &ArticleManager::articleCreated, this, &MainWindow::onArticleCreated);
    connect(manager, &ArticleManager::articleListFetched, this, &MainWindow::onArticleListFetched);
    connect(manager, &ArticleManager::articleFetched, this, &MainWindow::onArticleFetched);
    connect(manager, &ArticleManager::operationFailed, this, &MainWindow::onOperationFailed);

    manager->fetchArticleList();

    ui->tabWidget->removeTab(0);

}

MainWindow::~MainWindow()
{

}

/**
 * @brief 文章创建结果回调
 * @param success 创建成功标志
 * @param message 服务器返回的消息
 */
void MainWindow::onArticleCreated(bool success, const QString &message)
{
    if (!success) {
        QMessageBox::warning(this, "错误", message);
    }
    ui->pb_create->setEnabled(true);
    manager->fetchArticleList();
}

void MainWindow::onArticleUpdated(bool success, const QString &message)
{

}

/**
 * @brief 获取文章列表成功
 * @param articles 文章列表
 */
void MainWindow::onArticleListFetched(const QList<QJsonObject> &articles)
{
    ui->article_list->clear();

    for (auto var : articles) {
        auto map = var.toVariantMap();

        struct Article article = Article::fromVariantMap(map);

        QListWidgetItem *item = new QListWidgetItem(article.title);
        item->setData(990, article.article_id);
        ui->article_list->addItem(item);
    }

    if (isFirst) {
        ui->article_list->setCurrentRow(0);
        isFirst = false;
    } else {
        ui->article_list->setCurrentRow(ui->article_list->count() - 1);
    }
}

/**
 * @brief 获取文章成功回调
 * @param object 文章对象
 */
void MainWindow::onArticleFetched(const QJsonObject &object)
{
    // 将文章对象转为结构体
    Article article = Article::fromVariantMap(object.toVariantMap());

    // 设置标题与内容
    ui->article_title->setText(article.title);
    ui->article_content->setText(article.content);

    connect(ui->article_title, &QLineEdit::textChanged, this, &MainWindow::slot_article_title_textChanged);
    connect(ui->article_content, &QTextEdit::textChanged, this, &MainWindow::slot_article_content_textChanged);

    ui->article_list->setEnabled(true);
}

void MainWindow::onOperationFailed(const QString &error)
{
    qDebug() << error;
}

/**
 * @brief 列表筛选
 */
void MainWindow::on_artcle_list_filter_textChanged(const QString &arg1)
{
    // 1. 拿到所有 item 都显示
    int count = ui->article_list->count();
//    for (int i = 0; i < count; ++i) {
//        auto item = ui->article_list->item(i);
//        item->setHidden(false);
//    }

    // 2. 拿到所有 item 都显示
    for (int i = 0; i < count; ++i) {
        auto item = ui->article_list->item(i);
        if (item->text().contains(arg1, Qt::CaseInsensitive)) {
            item->setHidden(false);
        } else {
            item->setHidden(true);
        }
    }
}

/**
 * @brief 创建文章按钮回调
 */
void MainWindow::on_pb_create_clicked()
{
    ui->pb_create->setEnabled(false);
    // 创建文章{默认文章信息}
    Article article = {
        0,
        "新建标题" + QString::number(ui->article_list->count()),
        "新建内容" + QString::number(ui->article_list->count()),
        {}
    };
    manager->createArticle(article);
}

/**
 * @brief 文章列表选中项改变
 */
void MainWindow::on_article_list_currentItemChanged(QListWidgetItem *current, QListWidgetItem *previous)
{
    ui->article_title->disconnect();
    ui->article_content->disconnect();

    if (!current) {
        return;
    }
    ui->article_list->setEnabled(false);

    // todo: save previous?

    int article_id = current->data(990).toInt();
    manager->fetchArticleById(article_id);
}

/**
 * @brief 文章标题内容改变
 * @param arg1 文章标题文本
 */
void MainWindow::slot_article_title_textChanged(const QString &arg1)
{
    auto current = ui->article_list->currentItem();
    if (!current) {
        return;
    }

    struct Article article;
    article.article_id = current->data(990).toInt();
    article.title = ui->article_title->text();
    article.content = ui->article_content->toPlainText();
    article.images = QStringList();

    current->setText(article.title);
    manager->updateArticle(article);
}

/**
 * @brief 文章内容改变
 */
void MainWindow::slot_article_content_textChanged()
{
    auto current = ui->article_list->currentItem();
    if (!current) {
        return;
    }

    struct Article article;
    article.article_id = current->data(990).toInt();
    article.title = ui->article_title->text();
    article.content = ui->article_content->toPlainText();
    article.images = QStringList();

    manager->updateArticle(article);
}

/**
 * @brief 显示菜单
 */
void MainWindow::on_pb_article_to_image_clicked()
{
    QMenu menu;
    menu.addAction(ui->action_article_to_image);
    menu.exec(QCursor::pos());
}

/**
 * @brief 将文章转为图片
 */
void MainWindow::on_action_article_to_image_triggered()
{
    auto current = ui->article_list->currentItem();
    if (!current) {
        return;
    }

    QPixmap pixmap1 = QPixmapMeger::pixmap_from_lineedit(ui->article_title);
    QPixmap pixmap2 = QPixmapMeger::pixmap_from_textedit(ui->article_content);

    QPixmap pixmap = QPixmapMeger::pixmap_merge(pixmap1, pixmap2, true);

    QApplication::clipboard()->setPixmap(pixmap);
}

/**
 * @brief 文本编辑器自动换行设置
 */
void MainWindow::on_cb_wordwrap_stateChanged(int arg1)
{
    ui->article_content->setLineWrapMode(ui->cb_wordwrap->isChecked()
        ? QTextEdit::LineWrapMode::WidgetWidth : QTextEdit::LineWrapMode::NoWrap);
}

